<template>
  <div id="app" style="width: 85vw;">
    <div class="content-header">
      <h1>功能管理<small>线路管理</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>功能管理</el-breadcrumb-item>
        <el-breadcrumb-item>线路管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="app-container">
      <div class="box">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input
              v-model="queryParams.queryString"
              placeholder="请输入线路ID或名称"
              style="width: 200px"
              @keyup.enter="handleQuery"
              clearable
          >
            <template #append>
              <el-button @click="handleQuery">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          <el-button type="primary" @click="handleAdd">新增线路</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </div>

    <!-- 数据表格 -->
    <el-table
        :data="routeList"
        border
        style="width: 100%"
        v-loading="loading"
        highlight-current-row
        stripe
    >
      <el-table-column prop="routeId" label="线路编号" width="120" />
      <el-table-column prop="routeName" label="线路名称" width="150" />
      <el-table-column prop="departurePlace" label="出发地" width="150" />
      <el-table-column prop="destination" label="目的地" width="150" />
      <el-table-column prop="departureTime" label="出发时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.departureTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="arrivalTime" label="到达时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.arrivalTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="vehicleId" label="车辆编号" width="120" />
      <el-table-column prop="isOperating" label="运营状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isOperating ? 'success' : 'danger'">
            {{ scope.row.isOperating ? '运营中' : '已停运' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operatingPeriod" label="运营周期" width="170" />
      <el-table-column prop="routeDescription" label="线路描述" width="230" show-overflow-tooltip />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="queryParams.currentPage"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialog.title"
        v-model="dialog.visible"
        width="700px"
        @close="resetForm"
        destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="线路编号" prop="routeId">
              <el-input v-model="form.routeId" placeholder="请输入线路名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线路名称" prop="routeName">
              <el-input v-model="form.routeName" placeholder="请输入线路名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆编号" prop="vehicleId">
              <el-input v-model="form.vehicleId" placeholder="请输入车辆编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出发地" prop="departurePlace">
              <el-input v-model="form.departurePlace" placeholder="请输入出发地" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目的地" prop="destination">
              <el-input v-model="form.destination" placeholder="请输入目的地" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出发时间" prop="departureTime">
              <el-date-picker
                  v-model="form.departureTime"
                  type="datetime"
                  placeholder="选择出发时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到达时间" prop="arrivalTime">
              <el-date-picker
                  v-model="form.arrivalTime"
                  type="datetime"
                  placeholder="选择到达时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运营状态" prop="isOperating">
              <el-switch
                  v-model="form.isOperating"
                  :active-value="true"
                  :inactive-value="false"
                  active-text="运营中"
                  inactive-text="已停运"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运营周期" prop="operatingPeriod">
              <el-input v-model="form.operatingPeriod" placeholder="请输入运营周期" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="线路描述" prop="routeDescription">
          <el-input
              v-model="form.routeDescription"
              type="textarea"
              rows="3"
              placeholder="请输入线路描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </div>
  </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import request from '@/util/http' // 假设您有一个请求工具

// 查询参数
const queryParams = reactive({
  queryString: '',
  currentPage: 1,
  pageSize: 10
})

// 数据相关
const loading = ref(false)
const submitLoading = ref(false)
const routeList = ref([])
const total = ref(0)
const formRef = ref(null)

// 对话框数据
const dialog = reactive({
  visible: false,
  title: '',
  type: 'add'
})

// 表单数据
const form = reactive({
  routeId: undefined,
  routeName: '',
  departurePlace: '',
  destination: '',
  departureTime: null,
  arrivalTime: null,
  vehicleId: '',
  isOperating: true,
  operatingPeriod: '',
  routeDescription: ''
})

// 表单验证规则
const rules = {
  routeName: [
    { required: true, message: '请输入线路名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  departurePlace: [
    { required: true, message: '请输入出发地', trigger: 'blur' }
  ],
  destination: [
    { required: true, message: '请输入目的地', trigger: 'blur' }
  ],
  departureTime: [
    { required: true, message: '请选择出发时间', trigger: 'change' }
  ],
  arrivalTime: [
    { required: true, message: '请选择到达时间', trigger: 'change' }
  ],
  // vehicleId: [
  //   { required: true, message: '请输入车辆编号', trigger: 'blur' }
  // ],
  operatingPeriod: [
    { required: true, message: '请输入运营周期', trigger: 'blur' }
  ]
}

// API请求方法
const api = {
  // 获取列表
  getList: (params) => request.get('/admin/xianlu/findPage', { params }),
  // 获取详情
  getDetail: (id) => request.get(`/admin/xianlu/${id}`),
  // 新增
  add: (data) => request.post('/admin/xianlu/add', data),
  // 修改
  update: (data) => request.put('/admin/xianlu/update', data),
  // 删除
  delete: (id) => request.delete(`/admin/xianlu/${id}`)
}

// 查询数据
const handleQuery = async () => {
  loading.value = true
  try {
    const { data } = await api.getList(queryParams)
    if (data.flag) {
      routeList.value = data.data.records
      total.value = data.data.total
    } else {
      ElMessage.error(data.message)
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.queryString = ''
  handleQuery()
}

// 新增按钮
const handleAdd = () => {
  resetForm()
  dialog.type = 'add'
  dialog.title = '新增线路'
  dialog.visible = true
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    const { data } = await api.getDetail(row.routeId)
    if (data.flag) {
      dialog.type = 'edit'
      dialog.title = '编辑线路'
      Object.assign(form, data.data)
      dialog.visible = true
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该线路吗？', '警告', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const { data } = await api.delete(row.routeId)
      if (data.flag) {
        ElMessage.success('删除成功')
        handleQuery()
      } else {
        ElMessage.error(data.message)
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const apiMethod = dialog.type === 'add' ? api.add : api.update
        const { data } = await apiMethod(form)
        if (data.flag) {
          ElMessage.success(dialog.type === 'add' ? '新增成功' : '修改成功')
          dialog.visible = false
          handleQuery()
        } else {
          ElMessage.error(data.message)
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    routeId: undefined,
    routeName: '',
    departurePlace: '',
    destination: '',
    departureTime: null,
    arrivalTime: null,
    vehicleId: '',
    isOperating: true,
    operatingPeriod: '',
    routeDescription: ''
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  handleQuery()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.currentPage = val
  handleQuery()
}

// 日期时间格式化
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 初始化
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.route-manage {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  margin-right: 5px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>